'''
Author: wuxiangyi
Date: 2022-05-30 19:53:39
LastEditors: wuxiangyi
LastEditTime: 2022-05-31 15:36:44
FilePath: /毕业论文自动化系统/utils/WordWriter.py
Description: 

'''
from unicodedata import name
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT  # 表格样式设计操作
from docx.enum.text import WD_ALIGN_PARAGRAPH
from textrank4zh import TextRank4Keyword, TextRank4Sentence  # 从文本从提取关键词、句相关
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox, QFileDialog, QTableWidgetItem, QHeaderView  # 窗体工具相关
from docx.shared import Cm, Pt  # 设置docx文档字体大小样式
from datetime import datetime  # 时间
import os  # 文件相关操作
import sys
from tkinter import font  # 额外接受参数操作
import openpyxl  # xlsx表格操作
from docx import Document  # docx文档操作

# 生成文档
def generateWord(record):
    number = record['number']
    className = record['className']
    studentNumber = record['studentNumber']
    name = record['name']
    phoneNumber = record['phoneNumber']
    title = record['title']
    instructorScore = record['instructorScore']
    interimExaminationScore = record['interimExaminationScore']
    taskCompleted = record['taskCompleted']
    tasksToBeCompleted = record['tasksToBeCompleted']
    problemsAndSolutions = record['problemsAndSolutions']
    document = Document(os.path.join(f'/Users/wuxiangyi/Desktop','毕业设计中期检查表模板.docx'))
    table = document.tables[0]

    # 姓名 班级 序号
    row0 = table.rows[0]
    row0.cells[1].text = name
    row0.cells[3].text = className
    row0.cells[6].text = studentNumber
    setTextCenter(row0)
    setLineSpacing(row0)

    # 题目
    row1 = table.rows[1]
    row1.cells[1].text = title
    row1.cells[1].paragraphs[0].runs[0].bold = True
    setLineSpacing(row1)
    setTextCenter(row1)

    # 目前已完成任务
    row2 = table.rows[2]
    row2.cells[1].text = taskCompleted
    setLineSpacing(row2)
    setTextLeft(row2)

    # 尚需完成任务
    row4 = table.rows[4]
    row4.cells[1].text = tasksToBeCompleted
    setLineSpacing(row4)
    setTextLeft(row4)

    # 存在的问题及解决办法
    row6 = table.rows[6]
    row6.cells[1].text = problemsAndSolutions
    setLineSpacing(row6)
    setTextLeft(row6)

    # 写入分数
    row = table.rows[7]
    paragraphs = row.cells[1].paragraphs[0]
    scoreRun = paragraphs.add_run(str(instructorScore))
    scoreRun.font.size = Pt(15)
    scoreRun.font.name = '宋体'
    scoreRun.bold = True
    # 判断文件是否存在
    #####################################################
    title = title.replace('/' , '')
    if not os.path.exists(f'{getRunFilePath()}/GenerateWord'):
        os.mkdir(f'{getRunFilePath()}/GenerateWord')
    if not os.path.exists(f'{getRunFilePath()}/GenerateWord/{name}'):
        os.mkdir(f'{getRunFilePath()}/GenerateWord/{name}')
    document.save(os.path.join(f"{getRunFilePath()}/GenerateWord/{name}",
                                f'{title}.docx'))
    # try:
        
    # except:
        # QMessageBox.critical(None, "文档生成错误", f"生成文档时出现错误：\n")

# 设置行距
def setLineSpacing(row):
    for cell in row.cells:  # 所有单元格
        for paragraph in cell.paragraphs:  # 所有段落
            paragraph.paragraph_format.line_spacing = 2

# 设置居左
def setTextLeft(row):
    cell = row.cells[1]
    for paragraph in cell.paragraphs:  # 所有段落
        paragraph.paragraph_format.alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER  # 垂直对齐，居中
        paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
        for run in paragraph.runs:
            font = run.font
            font.size = Pt(12)

# 设置居中
def setTextCenter(row):
    '''
    设置表格样式中的居中
    Parameters
    ----------
    row：表格中的行

    Returns
    -------
    无
    '''
    for cell in row.cells:  # 所有单元格
        for paragraph in cell.paragraphs:  # 所有段落
            paragraph.paragraph_format.alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER  # 垂直对齐，居中
            for run in paragraph.runs:
                font = run.font
                font.size = Pt(12)

# 获取当前文件路径
def getRunFilePath():
    '''
    会判断是Exe可执行程序还是Python文件，获取当前执行程序的文件夹路径
    Returns
    -------
    文件执行路径
    '''
    application_path = ''
    application_path = os.path.dirname(os.path.dirname(__file__))
    return application_path

if __name__ == "__main__":
    record = {
        'number': 16,
        'className': '计科61807',
        'studentNumber': '201862104',
        'name': '柯娅娅',
        'phoneNumber': '17371774770',
        'title': '基于Vue框架的企业流程引擎的设计与实现',
        # 指导老师分数
        'instructorScore': 95,
        # 中期检查报告分数
        'interimExaminationScore': 95,
        # 目前已完成任务
        'taskCompleted': '1、系统Web框架页面设计，接口设计，后台数据库设计\n\
2、前端页面详细设计，WebSocket实时通信交互设计\n\
3、后台服务数据接口详细设计与实现\n\
4、前端和后台数据接口的联调',
        # 尚需完成的任务
        'tasksToBeCompleted': '1、系统缺陷测试\n\
2、前后端代码进行检查\n\
3、系统界面优化\n\
4、毕业论文的撰写，格式调整，内容修改',
        # 存在的问题及解决办法
        'problemsAndSolutions': '问题：交互数据不够稳定，易出现数据丢失和粘包问题\n\
办法：将数据封装以特定数据开头和结尾数据段，对数据进行拼包和数据丢弃。'
    }
    generateWord(record)